/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef NODE_HTTP2_HANDLE_SHAKE_H
#define NODE_HTTP2_HANDLE_SHAKE_H

#include "napi/http2_constant.h"
#include "nghttp2/nghttp2.h"
#include "ohos_log.h"
#include "openssl/err.h"
#include "openssl/ossl_typ.h"
#include "openssl/ssl.h"
#include "openssl/tls1.h"
#include <fcntl.h>
#include <netinet/in.h>
#include <string>
#include <netinet/tcp.h>
#include <map>
#include <poll.h>
#include <cstdio>
#include <netdb.h>
#include <unistd.h>
#include <nghttp2/nghttp2.h>
#include <fcntl.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <unordered_map>
#include "ohos_log.h"
#include "http2_struct.h"
#include "napi/native_api.h"
#include "http2_constant.h"
#include "http2_map.h"
#include "utils/napi/napi_utils.h"
#include <uv.h>
#include "http2_utils.h"

int SelectNextProtoCb(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in,
                      unsigned int inlen, void *arg)
{
    int rv = 0;
    rv = nghttp2_select_next_protocol(out, outlen, in, inlen);
    if (rv <= 0) {
        LOGE("Server did not advertise HTTP/2 protocol");
    }
    return SSL_TLSEXT_ERR_OK;
}

bool InitSslCtx(SSL_CTX *sslCtx, Connection *connection)
{
    SSL_CTX_set_options(sslCtx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
    SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY);
    SSL_CTX_set_mode(sslCtx, SSL_MODE_RELEASE_BUFFERS);
    SSL_CTX_set_next_proto_select_cb(sslCtx, SelectNextProtoCb, nullptr);
    std::string alpnProtos = "\x02h2";
    const unsigned char* protos = reinterpret_cast<const unsigned char*>(alpnProtos.c_str());
    SSL_CTX_set_alpn_protos(sslCtx, protos, NUM_3);
    if (!connection->ca.empty() && (connection->ca != "undefined") &&
        (SSL_CTX_load_verify_locations(sslCtx, connection->ca.c_str(), nullptr) <= 0)) {
        LOGE("Failed to load CA certificate: %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    if (!connection->cert.empty() && (connection->cert != "undefined") &&
        (SSL_CTX_use_certificate_file(sslCtx, connection->cert.c_str(), SSL_FILETYPE_PEM) <= 0)) {
        LOGE("Failed to load client certificate: %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    if (!connection->key.empty() && (connection->key != "undefined") &&
        (SSL_CTX_use_PrivateKey_file(sslCtx, connection->key.c_str(), SSL_FILETYPE_PEM) <= 0)) {
        LOGE("Failed to load client private key: %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    if (!connection->cert.empty() && !connection->key.empty() &&
        (connection->cert != "undefined") && (connection->key != "undefined") &&
        (SSL_CTX_check_private_key(sslCtx) <= 0)) {
        LOGE("Client private key does not match certificate: %s", ERR_error_string(ERR_get_error(), nullptr));
        return false;
    }
    return true;
}

int OpenSSLConnectHandle(SSL *ssl, int fd, std::string host)
{
    std::size_t hostLen = host.find(':');
    std::string domainName = host.substr(0, hostLen);
    LOGE("ssl_handshake host %s domain %s fd %d", host.c_str(), domainName.c_str(), fd);
    int rv = 0;
    if (SSL_set_fd(ssl, fd) == 0) {
        LOGE("SSL_set_fd %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    ERR_clear_error();
    SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
             static_cast<void*>(const_cast<char*>(domainName.c_str())));
    rv = SSL_connect(ssl);
    if (rv <= 0) {
        LOGE("SSL_connect %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    return rv;
}

void MakeNonBlock(int fd)
{
    int flags;
    int rv;
    while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR) {
        if (flags == -1) {
            LOGE("fcntl %s", strerror(errno));
        }
    }
    while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR) {
        if (rv == -1) {
            LOGE("fcntl end %s", strerror(errno));
        }
    }
}

void SetTcpNodelay(int fd)
{
    int val = 1;
    int rv = 0;
    rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, static_cast<socklen_t>(sizeof(val)));
    if (rv == -1) {
        LOGE("setsockopt %s", strerror(errno));
    }
}

bool IsDestroyed(const string& reqId)
{
    bool checkResult = CheckReqId(&reqId);
    if (!checkResult) {
        LOGE("IsDestroyed CheckReqId false");
        return true;
    }
    bool result = false;
    auto it = g_sessionManagerMap.Find(reqId);
    try {
        if (it != g_sessionManagerMap.End()) {
            result = it->second;
        }
    } catch (const std::out_of_range& e) {
        result = true;
        LOGE("Error IsDestroyed out_of_range reqId %s", reqId.c_str());
    }
    return result;
}

void SetCallBackRef(string reqId, const napi_ref &callbackRef)
{
    LOGE("setCallBackRef reqId %s callbackRef %p", reqId.c_str(), callbackRef);
    g_callbackManagerMap[reqId] = callbackRef;
}

void SetEnvMessage(string requestID, const napi_env &env)
{
    LOGE("setEnvMessage reqId %s env %p", requestID.c_str(), env);
    g_envManagerMap[requestID] =  env;
}

void FreeRequestCallback(RequestCallback *requestCallback)
{
    delete requestCallback;
    requestCallback = nullptr;
}

void EndStreamTask(napi_env env, void *data)
{
    if (!data) {
        return;
    }
    Connection *connection = (Connection *)data;
    LOGE("EndStreamTask reqId %s", connection->reqId.c_str());
    napi_value result;
    if (!CheckReqId(&connection->reqId)) {
        return;
    }
    napi_status napi_status = napi_create_string_utf8(env, connection->reqId.c_str(), NAPI_AUTO_LENGTH, &result);
    if ((napi_status == napi_ok) && connection->env && connection->deferred) {
        napi_resolve_deferred(connection->env, connection->deferred, result);
    }
    napi_delete_async_work(env, connection->asyncWork);
}

void EndWriteTask(napi_env env, void *data)
{
    if (!data) {
        return;
    }
    RequestTask *requestTask = (RequestTask *)data;
    if (requestTask->asyncWork) {
        napi_delete_async_work(env, requestTask->asyncWork);
    }
    LOGE("EndWriteTask reqId %s", requestTask->reqId.c_str());
    if (!CheckReqId(&requestTask->reqId)) {
        return;
    }
    if (requestTask->buff) {
        free(requestTask->buff);
        requestTask->buff = nullptr;
    }
    delete requestTask;
    requestTask = nullptr;
}

void FreeMapByReqId(string reqId)
{
    if (!CheckReqId(&reqId)) {
        return;
    }
    bool isDuplexStream = false;
    auto requestManagerIt = g_requestManagerMap.Find(reqId);
    if (requestManagerIt != g_requestManagerMap.End()) {
        auto requestTask = requestManagerIt->second;
        if (requestTask->rpcType == DUPLEX_STREAM_RPC) {
            isDuplexStream = true;
        }
    }
    if (g_envManagerMap.Find(reqId) != g_envManagerMap.End() && !isDuplexStream) {
        g_envManagerMap.Erase(reqId);
    }
    if (g_connectManagerMap.Find(reqId) != g_connectManagerMap.End() && !isDuplexStream) {
        g_connectManagerMap.Erase(reqId);
    }
    if (requestManagerIt != g_requestManagerMap.End() && !isDuplexStream) {
        delete requestManagerIt->second;
        g_requestManagerMap.Erase(reqId);
    }
    if (g_callJsCheckDataManagerMap.Find(reqId) != g_callJsCheckDataManagerMap.End()) {
        g_callJsCheckDataManagerMap.Erase(reqId);
    }
    if (g_responseHeadersManagerMap.Find(reqId) != g_responseHeadersManagerMap.End()) {
        g_responseHeadersManagerMap.Erase(reqId);
    }
    LOGE("FreeMapByReqId success reqId %s", reqId.c_str());
}

void DeleteCallBackRef(napi_env env, const string reqId)
{
    if (CheckReqId(&reqId)) {
        auto requestManagerIt = g_requestManagerMap.Find(reqId);
        if (requestManagerIt != g_requestManagerMap.End()) {
            auto request = requestManagerIt->second;
            if (request->rpcType == DUPLEX_STREAM_RPC) {
                return;
            }
        }
        auto callbackManagerIt = g_callbackManagerMap.Find(reqId);
        if (callbackManagerIt != g_callbackManagerMap.End()) {
            LOGE("DeleteCallBackRef delete success reqId %s", reqId.c_str());
            auto callbackRef = callbackManagerIt->second;
            napi_delete_reference(env, callbackRef);
            g_callbackManagerMap.Erase(reqId);
            FreeMapByReqId(reqId);
        }
    }
}
#endif //NODE_HTTP2_HANDLE_SHAKE_H
